package com.kgc.kmall.kmallorderweb.controller;

import com.google.common.collect.Ordering;
import com.kgc.kmall.annotations.LoginRequired;
import com.kgc.kmall.bean.MemberReceiveAddress;
import com.kgc.kmall.bean.OmsCartItem;
import com.kgc.kmall.bean.OmsOrder;
import com.kgc.kmall.bean.OmsOrderItem;
import com.kgc.kmall.service.CartService;
import com.kgc.kmall.service.MemberService;
import com.kgc.kmall.service.OrderService;
import com.kgc.kmall.service.SkuService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Controller
public class OrderController {

    @Reference
    MemberService memberService;

    @Reference
    CartService cartService;

    @Reference
    OrderService orderService;

    @Reference
    SkuService skuService;

    @RequestMapping("/toTrade")
    @LoginRequired(value = true)
    public String toTrade(HttpServletRequest request, Model model){
//        显示地址
        Integer memberId = (Integer) request.getAttribute("memberId");
        String nickname = (String) request.getAttribute("nickname");
        List<MemberReceiveAddress> umsMemberReceiveAddresses = memberService.getReceiveAddressByMemberId(Long.valueOf(memberId));
        System.out.println("登录信息"+memberId);
        for (MemberReceiveAddress umsMemberReceiveAddress : umsMemberReceiveAddresses) {
            System.out.println(umsMemberReceiveAddress.getName());
        }
        model.addAttribute("userAddressList",umsMemberReceiveAddresses);
        //显示购物车
        List<OmsCartItem> omsCartItems = cartService.cartList(memberId + "");
        List<OmsOrderItem> omsOrderItemList=new ArrayList<>();
        for (OmsCartItem omsCartItem : omsCartItems) {
            if(omsCartItem.getIsChecked().equals("1")){
                OmsOrderItem omsOrderItem=new OmsOrderItem();
                omsOrderItem.setProductName(omsCartItem.getProductName());
                omsOrderItem.setProductPic(omsCartItem.getProductPic());
                omsOrderItem.setProductQuantity(omsCartItem.getQuantity());
                omsOrderItemList.add(omsOrderItem);
            }
        }
        model.addAttribute("omsOrderItems", omsOrderItemList);
        model.addAttribute("totalAmount", getTotalAmount(omsCartItems));

        //生成交易吗

        String tradeCode = orderService.genTradeCode(Long.valueOf(memberId));
        System.out.println(tradeCode);
        model.addAttribute("tradeCode", tradeCode);
        return "trade";
    }

    public BigDecimal getTotalAmount( List<OmsCartItem> omsCartItems){
        BigDecimal bigDecimal=new BigDecimal(0);
        for (OmsCartItem omsCartItemItem : omsCartItems) {
            bigDecimal=bigDecimal.add(omsCartItemItem.getPrice().multiply(new BigDecimal(omsCartItemItem.getQuantity())));
        }
        return bigDecimal;
    }


    @LoginRequired(value=true)
    @RequestMapping("/submitOrder")
    public String submitOrder(String receiveAddressId, BigDecimal totalAmount, String tradeCode, HttpServletRequest request, HttpServletResponse response, HttpSession session, ModelMap modelMap) {
        //从拦截器中获取用户memberid和nickname
        Integer memberId = (Integer) request.getAttribute("memberId");
        String nickname = (String) request.getAttribute("nickname");
        // 检查交易码
        String success = orderService.checkTradeCode(Long.valueOf(memberId), tradeCode);
        //若是交易码不一样则直接返回过去
        if(!success.equals("success")){
            return "tradeFail";
        }else{
            List<OmsOrderItem> omsOrderItemList=new ArrayList<>();
            //订单对象
            OmsOrder omsOrder=new OmsOrder();
            omsOrder.setAutoConfirmDay(7);
            omsOrder.setCreateTime(new Date());
            omsOrder.setDiscountAmount(null);
            omsOrder.setMemberId(Long.valueOf(memberId));
            omsOrder.setMemberUsername(nickname);
            omsOrder.setNote("快点发货");
            //生成订单码
            String outTradeNo="kmall";
            outTradeNo=outTradeNo+System.currentTimeMillis();
            SimpleDateFormat sdf=new SimpleDateFormat("YYYYMMDDHHmmss");
            outTradeNo=outTradeNo+sdf.format(new Date());
            omsOrder.setOrderSn(outTradeNo);
            omsOrder.setPayAmount(totalAmount);
            omsOrder.setOrderType(1);
            MemberReceiveAddress receiveAddressByMemberId = memberService.getReceiveAddressById(Long.parseLong(receiveAddressId));
            omsOrder.setReceiverCity(receiveAddressByMemberId.getCity());
            omsOrder.setReceiverDetailAddress(receiveAddressByMemberId.getDetailAddress());
            omsOrder.setReceiverName(receiveAddressByMemberId.getName());
            omsOrder.setReceiverPhone(receiveAddressByMemberId.getPhoneNumber());
            omsOrder.setReceiverPostCode(receiveAddressByMemberId.getPostCode());
            omsOrder.setReceiverProvince(receiveAddressByMemberId.getProvince());
            omsOrder.setReceiverRegion(receiveAddressByMemberId.getRegion());
            //当前日期加一天,一天后配送
            Calendar c=Calendar.getInstance();
            c.add(Calendar.DATE,1);
            Date time=c.getTime();
            omsOrder.setReceiveTime(time);
            omsOrder.setSourceType(0);
            omsOrder.setStatus(0);
            omsOrder.setOrderType(0);
            omsOrder.setTotalAmount(totalAmount);
            //根据用户id获得要购买的商品列表,和总价格
            List<OmsCartItem> omsCartItems = cartService.cartList(memberId.toString());
            for (OmsCartItem omsCartItem : omsCartItems) {
                if(omsCartItem.getIsChecked().equals("1")){
                    OmsOrderItem omsOrderItem=new OmsOrderItem();
                    boolean b=skuService.checkPrice(omsCartItem.getProductSkuId(),omsCartItem.getPrice());
                    if(!b){
                        return "tradeFail";
                    }
                    omsOrderItem.setProductPic(omsCartItem.getProductPic());
                    omsOrderItem.setProductName(omsCartItem.getProductName());
                    omsOrderItem.setOrderSn(outTradeNo);
                    omsOrderItem.setProductCategoryId(omsCartItem.getProductCategoryId());
                    omsOrderItem.setProductPrice(omsCartItem.getPrice());
                    omsOrderItem.setRealAmount(omsCartItem.getTotalPrice());
                    omsOrderItem.setProductQuantity(omsCartItem.getQuantity());
                    omsOrderItem.setProductSkuCode("111111111");
                    omsOrderItem.setProductSkuId(omsCartItem.getProductSkuId());
                    omsOrderItem.setProductSn("仓库对应的商品编号");
                    omsOrderItemList.add(omsOrderItem);
                }
            }
            omsOrder.setOrderItems(omsOrderItemList);
            orderService.saveOrder(omsOrder);
            return "redirect:http://payment.kmall.com:8088/index?outTradeNo="+outTradeNo+"&totalAmount="+totalAmount;
        }
    }

}
